const fs = require('fs')
const path = require('path')
const query = require('../db/query')
const dbPath = path.join('/Users/HUAWEI/Desktop/node/zuoye0929/app/db','/userDb.json')

const addUserService = async(params)=>{
    let myData = await JSON.parse(fs.readFileSync(dbPath,'utf-8'))
    myData.push(params)
    await fs.writeFileSync(dbPath,JSON.stringify(myData),'utf-8')
    return true
    
    // console.log(params,'121212');
    // console.log(path.join(__dirname,'./user.json'))
    // const dbPath = path.join(__dirname,'./user.json')
}


const delUserService = async(params)=>{
    let myData = await JSON.parse(fs.readFileSync(dbPath,'utf-8'))
    let arr=[]
    await myData.forEach(item => {
        if(item.id != params){
            arr.push(item)
        }
    })
    await fs.writeFileSync(dbPath,JSON.stringify(arr),'utf-8')
    return true
}

//查
const getListService = async(params)=>{
    const sql = `select*from users`
    const result = await query(sql)
    // console.log(result)
    return result
}

//增
const addListService = async(params)=>{
    const sql = `insert into users(username,pwd,age,phone,nickname) values('${params.username}',${params.pwd},${params.age},'${params.phone}''${params.nickname}')`
    const result = await query(sql)
    if(result.affectedRows == 1){

        return true
    }else {
        return false
    }
}


module.exports = {
    addUserService,
    delUserService,
    getListService ,
    addListService
}